package tt.dz.order.util.thirdrecord;

import java.math.BigDecimal;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.springframework.stereotype.Component;

import tt.dz.order.pojo.WeiXinPayCallBackRecord;
import tt.dz.order.util.OrderConstant.OrderPayChannelCode;
import tt.dz.order.util.ThreadSafeDateFormat;
import tt.dz.order.vo.ThdPayWayRecord;

/**
 *
 * 
 * @name weixin第三方支付查询
 * @author Anson
 * @version 1.0
 * @summary 通过订单号查询第三方的支付记录
 * @desc
 *
 */
@Component
public class WeiXinPayThirdRecordQuery extends AbstractCommonThirdRecordQuery {

	private static final String WEI_XIN_PAY_DATE_FMT = "yyyyMMddHHmmss";

	@Override
	public OrderPayChannelCode getThirdChannelCode() {
		return OrderPayChannelCode.weixinpay;
	}

	@Override
	public List<ThdPayWayRecord> query(List<String> orderNos) {
		List<WeiXinPayCallBackRecord> originalRecords = this.queryAliPayRecord(orderNos);
		List<ThdPayWayRecord> records = new ArrayList<ThdPayWayRecord>(0);
		if (originalRecords == null || originalRecords.isEmpty()) {
			return records;
		}
		ThdPayWayRecord record = null;
		for (WeiXinPayCallBackRecord r : originalRecords) {
			record = new ThdPayWayRecord();
			record.setOrderNo(r.getOrderNo());
			record.setTradeNo(r.getTradeNo());
			record.setTradeStatus(r.getReturnCode());
			record.setPayAmount(new BigDecimal(r.getTotalFee()));
			record.setPayChannelCode(this.getThirdChannelCode().value());
			record.setQuantity(null);
			record.setFinishTime(this.fmtDate(r.getTimeEnd()));
			records.add(record);
		}

		return records;
	}

	private String fmtDate(String orginalDateFmt) {
		String fmt = "";
		Date dt = null;
		try {
			dt = ThreadSafeDateFormat.parse(orginalDateFmt, WEI_XIN_PAY_DATE_FMT);
		} catch (ParseException e) {
			return fmt;
		}
		if (dt == null) {
			return fmt;
		}

		fmt = ThreadSafeDateFormat.format(dt, ThdPayWayRecord.TIME_FMT);
		return fmt;
	}

	/**
	 * 根据订单号查询回调信息
	 * 
	 * @param orderNos
	 * @return
	 */
	public List<WeiXinPayCallBackRecord> queryAliPayRecord(List<String> orderNos) {
		return WeiXinPayCallBackRecord.getByIds(orderNos);
	}
}
